/**
 * 
 */
package bi.uc.pay;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import bi.uc.client.ExitApplication;
import bi.uc.login.Info;

import com.bi_uc.www.R;
import com.zijunlin.Zxing.Demo.CaptureActivity;

public class PayActivity extends Activity implements OnClickListener {
	ListView mListView1;
	MyAdapter myAdapter;
	LinearLayout mHead;

	Info info = Info.getInfo();
	Button addGoods;
	Button scannning;
	EditText barCode;
	private static String TAG = "MainActivity";

	Button guest;
	Button cardUser;

	HashMap<String, HashMap<String, String>> goodsInfo = new HashMap<String, HashMap<String, String>>();
	public ArrayList<HashMap<String, String>> source = new ArrayList<HashMap<String, String>>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		((ExitApplication)getApplication()).addActivity(this);
		setContentView(R.layout.pay);
		guest = (Button) findViewById(R.id.guest);
		cardUser = (Button) findViewById(R.id.carduser);
		barCode = (EditText) findViewById(R.id.barcode);
		addGoods = (Button) findViewById(R.id.addgoods);
		scannning = (Button) findViewById(R.id.scan);

		guest.setOnClickListener(this);
		cardUser.setOnClickListener(this);
		scannning.setOnClickListener(this);
		addGoods.setOnClickListener(this);

		mHead = (LinearLayout) findViewById(R.id.head);
		mHead.setBackgroundResource(R.color.listHeadColor);
		mListView1 = (ListView) findViewById(R.id.listView1);

		myAdapter = new MyAdapter(this, R.layout.item);
		mListView1.setAdapter(myAdapter);
/*		mListView1.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean arg1) {
				// TODO Auto-generated method stub
				Log.e(TAG, "--------onFocusChange");
			}
		});
*/		
		
		mListView1.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Log.e(TAG, "--------setOnItemLongClickListener");
				Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
				vibrator.vibrate(40);
				myAdapter.setSelectedPosition(position);
				myAdapter.notifyDataSetChanged();
				return true;
			}

		});
		
	
		mListView1.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				MyAdapter.ViewHolder holder = (MyAdapter.ViewHolder) view
						.getTag();
				if (holder.txt1.isClickable()) {
					Log.i(TAG, "clickable");
				}
				Log.e(TAG, "--------setOnItemClickListener");
				myAdapter.setSelectedPosition(-1);
				myAdapter.notifyDataSetChanged();
			}
		});
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		Log.e(TAG, "onTouchEvent");
		super.onTouchEvent(event);
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			myAdapter.setSelectedPosition(-1);
			myAdapter.notifyDataSetChanged();
			Log.e(TAG, "onTouchEvent_down");
		}
		return true;
	}
	
	private class MyAdapter extends BaseAdapter {
		// public ArrayList<HashMap<String, String>> source = new
		// ArrayList<HashMap<String,String>>();
		int id_row_layout;
		LayoutInflater mInflater;

		private int selectedPosition = -1;// 选中的位置

		public MyAdapter(Context context, int id_row_layout) {
			super();
			this.id_row_layout = id_row_layout;
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return source.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return source.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public void setSelectedPosition(int position) {
			this.selectedPosition = position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parentView) {
			ViewHolder holder = null;
			if (convertView == null) {
				synchronized (PayActivity.this) {
					convertView = mInflater.inflate(id_row_layout, null);
					holder = new ViewHolder();
					holder.txt = (TextView) convertView
							.findViewById(R.id.column);
					holder.txt1 = (TextView) convertView
							.findViewById(R.id.column1);
					holder.txt2 = (TextView) convertView
							.findViewById(R.id.column2);
					holder.txt3 = (TextView) convertView
							.findViewById(R.id.column3);
					holder.linearLayout = (LinearLayout) convertView
							.findViewById(R.id.layout_other);
					holder.edit = (TextView) convertView
							.findViewById(R.id.item_edit);
					holder.delete = (TextView) convertView
							.findViewById(R.id.item_delete);
					convertView.setTag(holder);
				}
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			final HashMap<String, String> map = source.get(position);
			holder.txt.setText(map.get("商品"));
			holder.txt1.setText(map.get("单价"));
			holder.txt2.setText(map.get("数量"));
			holder.txt3.setText(map.get("总价"));

			int intervalColor1 = getResources()
					.getColor(R.color.intervalColor1);
			int intervalColor2 = getResources()
					.getColor(R.color.intervalColor2);
			int[] colors = { intervalColor1, intervalColor2 };// RGB颜色
			convertView.setBackgroundColor(colors[position % 2]);// 每隔item之间颜色不同
			if (selectedPosition == position) {
				convertView.setBackgroundColor(Color.GREEN);

				holder.linearLayout.setVisibility(View.VISIBLE);

				holder.edit.setClickable(true);

				holder.delete.setClickable(true);

				holder.edit.setOnClickListener(new OnClickListener() {

					EditText et = new EditText(PayActivity.this);
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						et.setInputType(InputType.TYPE_CLASS_NUMBER);
						new AlertDialog.Builder(PayActivity.this)
								.setTitle("输入购买商品数量")
								.setIcon(android.R.drawable.ic_dialog_info)
								.setView(et)
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												// TODO Auto-generated method
												// stub
												String s = et.getText().toString();
												if (!info.isExist(s)|| "0".equals(s)) {
													goodsInfo.remove(source.get(position).get("条码"));
													source.remove(position);
													selectedPosition = -1;
													notifyDataSetInvalidated();
												} else if (s.matches("^[0-9]*$")) {
													map.put("数量", s);							
													double sellingPrice = Double.parseDouble(map.get("单价"));
													int num = Integer.parseInt(s);
													map.put("总价",info.subZeroAndDot(Math.round(100*sellingPrice*num)/100.0+""));
													selectedPosition = -1;
													notifyDataSetInvalidated();
												}  
												
											}
										}).setNegativeButton("取消", null).show();
						
					}
				});

				holder.delete.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						selectedPosition = -1;
						goodsInfo.remove(source.get(position).get("条码"));
						source.remove(position);
						notifyDataSetChanged();
					}
				});
			} else {
				holder.linearLayout.setVisibility(View.GONE);
				holder.edit.setClickable(false);
				holder.delete.setClickable(false);
			}
			return convertView;
		}

		class ViewHolder {
			TextView txt;
			TextView txt1;
			TextView txt2;
			TextView txt3;
			public LinearLayout linearLayout;
			public TextView edit;
			public TextView delete;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.carduser:
			Intent intent = new Intent(PayActivity.this, CardUserActivity.class);
			intent.putExtra("goodsInfo", goodsInfo);
			intent.putExtra("source", source);
			startActivityForResult(intent, 2);
			break;
		case R.id.guest:
			Log.d("payactivity--goodsInfo:"+goodsInfo.size(), "source:"+source.size());
			Intent intent1 = new Intent(PayActivity.this, GuestActivity.class);
			intent1.putExtra("goodsInfo", goodsInfo);
			intent1.putExtra("source", source);
			startActivityForResult(intent1, 1);
			break;
		case R.id.addgoods:
			final String s = barCode.getText().toString();
			if ("".equals(s)) {
				Toast.makeText(PayActivity.this, "请输入需要添加的商品条码！",
						Toast.LENGTH_SHORT).show();
				return;
			}
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						checkGoods(s);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();

			break;

		case R.id.scan:
			Intent intent2 = new Intent(PayActivity.this, CaptureActivity.class);
			startActivityForResult(intent2, 0);
			break;
		default:
			break;
		}
	}

	/**
	 * 通过条码添加商品
	 * 
	 * @param s
	 *            商品条码
	 */
	private void checkGoods(String s) throws Exception {
		// TODO Auto-generated method stub
		String Url = "http://bi.bi-uc.com/BI.api";
		/*
		 * String Body = "Action=PDA-充值&商家=" + info.employID + "&店面=" +
		 * info.shopID + "&操作员=" + info.userID + "&卡号=" + cardNumString +
		 * "&充值金额=" + moneyString; Log.d("data", Body);
		 */
		Log.i("s", s);
		HttpPost httpRequest = new HttpPost(Url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair pair1 = new BasicNameValuePair("Action", "PDA-获取储值消费商品");
		NameValuePair pair2 = new BasicNameValuePair("商家", info.employID);
		NameValuePair pair3 = new BasicNameValuePair("店面", info.shopID);
		NameValuePair pair4 = new BasicNameValuePair("条码", s);

		params.add(pair1);
		params.add(pair2);
		params.add(pair3);
		params.add(pair4);

		HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
		httpRequest.setEntity(entity);
		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(httpRequest);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			/*
			InputStream in = response.getEntity().getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(in,
					"UTF-8"));
			StringBuffer responseMessage = new StringBuffer();
			int charCount = -1;
			while ((charCount = br.read()) != -1) {
				responseMessage.append((char) charCount);
			}
			Log.d("checkgoods", responseMessage.toString());
*/
			InputStream in = response.getEntity().getContent();// 接收服务器的数据
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory
					.newInstance(); // 获取XmlPullParser的实例
			final XmlPullParser parser = pullParserFactory.newPullParser();
			InputStreamReader responseReader = new InputStreamReader(in,
					"UTF-8");
			parser.setInput(responseReader);
			parser.next();
			int eventType = parser.getEventType();
			if (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG
						&& parser.getName().equals("XML")) { // String result =
					// parser.getAttributeValue(0);
					String result = parser.getAttributeValue(null, "EXEC");
					if (result.equals("True")) {
						HashMap<String, String> item = new HashMap<String, String>();
						HashMap<String, String> map = new HashMap<String, String>();
						if (null == goodsInfo.get(s)) {
							map.put("商品", parser.getAttributeValue(null,
									"pItem_Name"));
							item.put("pItem_Id",
									parser.getAttributeValue(null, "pItem_Id"));
							double sellPrice = Double.parseDouble(parser.getAttributeValue(null,"pItem_SellingPrice"));
							String string = info.subZeroAndDot(Math.round(100*sellPrice)/100.0+"");
							item.put("pItem_SellingPrice", string);
							map.put("数量", "1");
							map.put("单价", string);
							map.put("总价", string);
							map.put("条码", s);
							source.add(0, map);

							String discountRate = info.subZeroAndDot(parser.getAttributeValue(null,"pItem_DiscountRate"));
							item.put("pItem_DiscountRate", discountRate);
							String integralRate = info.subZeroAndDot(parser.getAttributeValue(null,"pItem_IntegralRate"));					
							item.put("pItem_IntegralRate", integralRate);
							item.put("pItem_IsSellByPrice", parser.getAttributeValue(null,"pItem_IsSellByPrice"));
							goodsInfo.put(s, item);
						} else {
							int length = source.size();
							for (int i = 0; i < length; i++) {
								HashMap<String, String> value = source.get(i);
								if (s.equals(value.get("条码"))) {
									int n = Integer.parseInt(value.get("数量"));
									double sellingPrice = Double.parseDouble(value.get("单价"));
									value.put("数量", n + 1+"");
									value.put("总价",info.subZeroAndDot(Math.round(100*sellingPrice*n)/100.0+""));
								}
							}
						}
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								myAdapter.setSelectedPosition(-1);
								myAdapter.notifyDataSetChanged();
								Log.i(TAG, "success");
							}
						});

					} else {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								Toast.makeText(PayActivity.this,
										parser.getAttributeValue(null, "错误消息"),
										Toast.LENGTH_SHORT).show();
							}
						});
						Log.d("data", parser.getAttributeValue(null, "错误消息"));
					}
				}
			}
			in.close();

			responseReader.close();
		} else {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(PayActivity.this, "连接超时，请确保网络连接正常！",
							Toast.LENGTH_SHORT).show();
				}
			});
		}

	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0:
			if (resultCode == Activity.RESULT_OK) {
				final String s = data.getCharSequenceExtra("code").toString();
				if ("".equals(s)) {
					Toast.makeText(PayActivity.this, "扫描条码为空，请重新扫描！",
							Toast.LENGTH_SHORT).show();
					return;
				}
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							checkGoods(s);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();
			}
			break;
		case 1:
			if (resultCode == Activity.RESULT_OK) {
				Toast.makeText(this, "散客储值消费成功！", Toast.LENGTH_SHORT).show();
				goodsInfo.clear();
				source.clear();
				barCode.setText("");
				myAdapter.notifyDataSetChanged();
			}
			break;
		case 2:
			if (resultCode == Activity.RESULT_OK) {
				Toast.makeText(this, "会员储值消费成功！", Toast.LENGTH_SHORT).show();
				goodsInfo.clear();
				source.clear();
				barCode.setText("");
				myAdapter.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}
	}

//	// 保留两位
//	public String formateRate(String rateStr) {
//		if (rateStr.indexOf(".") != -1) {
//			// 获取小数点的位置
//			int num = 0;
//			num = rateStr.indexOf(".");
//
//			// 获取小数点后面的数字 是否有两位 不足两位补足两位
//			String dianAfter = rateStr.substring(0, num + 1);
//			String afterData = rateStr.replace(dianAfter, "");
//			if (afterData.length() > 2) {
//				return rateStr.substring(0, num + 3);
//			} else {
//				return rateStr;
//			}
//
//		} else {
//			return rateStr;
//		}
//	}

}
